package com.example.bookmanage.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.bookmanage.constants.HttpConstants;
import com.example.bookmanage.result.Result;
import com.example.bookmanage.service.impl.TokenService;
import com.example.bookmanage.utils.JwtUtils;
import com.example.bookmanage.utils.ThreadLocalUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Value("${jwt.secret}")
    private String secret;

    /**
     * 延长token有效期
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        // 1. 获取token
        String token = request.getHeader(HttpConstants.AUTHENTICATION);
        response.setContentType("application/json; charset=utf-8");

        if (token == null || token.isEmpty()) {
            log.info("token为空");
            // 封装错误信息并转换为字符转返回
            Result<String> result = Result.fail(3001, "请登录!");
            response.getWriter().write(JSONObject.toJSONString(result));
            return false;
        } else {
            try {
                // 3. 解析token
                Claims claims = JwtUtils.parseToken(token, secret);
                Long userId = claims.get("userId", Long.class);
                ThreadLocalUtil.set("userId", userId);
                return true;
            } catch (Exception e) {
                log.info("token解析失败");
                // 4. 设置状态码, 响应错误信息
                response.setStatus(401);
                response.getWriter().write(JSONObject.toJSONString(Result.fail(3001, "登录已过期!")));
                return false;
            }
        }
    }
}
